package top.codecrab.cloudalibaba.service.impl;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.codecrab.cloudalibaba.client.AccountClient;
import top.codecrab.cloudalibaba.client.StorageClient;
import top.codecrab.cloudalibaba.entity.Order;
import top.codecrab.cloudalibaba.mapper.OrderMapper;
import top.codecrab.cloudalibaba.service.OrderService;

import javax.annotation.Resource;

/**
 * @author codecrab
 * @since 2021年05月21日 16:41
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private AccountClient accountClient;

    @Resource
    private StorageClient storageClient;

    /**
     * 创建订单 -> 调用库存服务扣减库存 -> 调用账户服务扣减账户余额 -> 修改订单状态
     * 简单说：
     * 下订单 -> 减库存 -> 减余额 -> 改状态
     */
    @Override
    @GlobalTransactional(name = "create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("--------订单微服务创建订单--------");
        orderMapper.create(order);

        log.info("--------订单微服务远程调用库存微服务扣减库存--------");
        storageClient.decrease(order.getProductId(), order.getCount());

        log.info("--------订单微服务远程调用账户微服务扣减账户余额--------");
        accountClient.decrease(order.getUserId(), order.getMoney(), order.isSuccess());

        log.info("--------订单微服务修改订单状态--------");
        orderMapper.updateStatusToComplete(order.getUserId(), 0);
    }
}
